package com.kh.statistics.video.core.script;

import com.alibaba.fastjson.JSON;
import com.kh.statistics.video.utils.SystemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.*;

/**
 * @author e-Hong.Kong
 */
@Slf4j
public class ShellExecutor {

    private static final Logger LOGGER = LoggerFactory.getLogger(ShellExecutor.class);

    public static Map<String, List<String>> executeScript(String path, String... command) {

        Map<String, List<String>> listMap = new HashMap<>();
        ProcessBuilder processBuilder = new ProcessBuilder();
        File file = new File(path);
        if (!file.exists()) {
            LOGGER.error("file:[" + path + "] not exist!");
            return listMap;
        }
        processBuilder.directory(file);
        processBuilder.command(command);
        log.info("执行的命令：{}", StringUtils.join(command, " "));

        BufferedReader inputReader = null;
        BufferedReader errorReader = null;
        List<String> returnString = new ArrayList<>();
        List<String> errorString = new ArrayList<>();
        listMap.put("normal", returnString);
        listMap.put("error", errorString);
        try {
            Process process = processBuilder.start();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //脚本执行输出信息
            inputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String str = null;
            while ((str = inputReader.readLine()) != null) {
                returnString.add(str);
            }
            //脚本执行异常时的输出信息
            errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String error = null;
            while ((error = inputReader.readLine()) != null) {
                returnString.add(error);
            }
            try {
                if (0 != process.waitFor()) {
                    throw new Exception(String.format("execute [%s] fail!(%s)", Arrays.toString(command), errorString));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputReader != null) {
                    inputReader.close();
                }
                if (errorReader != null) {
                    errorReader.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        LOGGER.info("normal return:" + JSON.toJSONString(returnString));
        LOGGER.info("error return:" + JSON.toJSONString(errorString));
        return listMap;
    }

    public static List<String> parseScript(String cmd) {
        String[] split = cmd.split(",");
        List<String> cmdList = new ArrayList<>(split.length);
        Collections.addAll(cmdList, split);
        return cmdList;
    }

    public static String parseParam(String param) {
        if (SystemUtil.isWindows()) {
            log.info("进入windows系统逻辑:{}", param);
            return "\"" + param + "\"";
        } else {
            return param;
        }
    }


    public static Map<String, List<String>> execute(String path, String... command) {
        Map<String, List<String>> listMap = new HashMap<>();
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        File file = new File(path);
        if (!file.exists()) {
            LOGGER.info("file:[" + path + "] not exist!");
            return listMap;
        }
        processBuilder.directory(file);

        LOGGER.info("执行的命令：" + String.join(" ", command));
        try {
            LOGGER.info("脚本开始执行");
            Process process = processBuilder.start();

            // 处理标准输出流
            StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");
            // 处理标准错误流
            StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");

            outputGobbler.start();
            errorGobbler.start();

            int exitCode = process.waitFor();
            outputGobbler.join();
            errorGobbler.join();

            listMap.put("normal", outputGobbler.getLines());
            listMap.put("error", errorGobbler.getLines());

            LOGGER.info("脚本执行结束，退出码：" + exitCode);
            System.out.println("Output: " + outputGobbler.getLines());
            System.out.println("Errors: " + errorGobbler.getLines());
            System.out.println("Exit Code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        return listMap;
    }

}